package ztrust

import (
	"encoding/json"
	"flare-admin/db/sqlc/ztrust"
)

func ZtrustScoreDao2DTOs(scores []ztrust.OteldemoZtScore) []ZtrustScoreDTO {
	var scoreDTOs []ZtrustScoreDTO
	for _, score := range scores {
		i64, err := score.CybertwinID.Int64Value()
		if err != nil {
			continue
		}

		CybertwinID := i64.Int64
		if CybertwinID < 0 {
			continue
		}

		scoreDTO := ZtrustScoreDTO{
			CybertwinID:  uint(CybertwinID),
			BasicScore:   float64(score.BasicScore) / 10000,
			DynamicScore: float64(score.DynamicScore) / 10000,
		}
		scoreDTOs = append(scoreDTOs, scoreDTO)
	}
	return scoreDTOs
}

func ZtrustEventDao2DTOs(events []ztrust.OteldemoZtEvent) []ZtrustEventDTO {
	var eventDTOs []ZtrustEventDTO
	for _, event := range events {
		i64, err := event.CybertwinID.Int64Value()
		if err != nil {
			continue
		}

		CybertwinID := i64.Int64
		if CybertwinID < 0 {
			continue
		}

		eventDTO := ZtrustEventDTO{
			ID:          int(event.ID),
			CybertwinID: uint(CybertwinID),
			Event:       event.Event,
			ScoreDesc:   event.ScoreDesc,
			EventDesc:   event.EventDesc,
			TriggerAt:   event.TriggerAt,
		}
		eventDTOs = append(eventDTOs, eventDTO)
	}
	return eventDTOs
}

func ZtrustAccessEventDAO2DTOs(records []ztrust.OteldemoCybertwinLoginRecord) []ZtrustAccessEventDTO {
	var accessEventDTOs []ZtrustAccessEventDTO

	for _, record := range records {
		var ev ZtrustAccessEventDTO
		if err := json.Unmarshal(record.Data, &ev); err != nil {
			continue
		}
		ev.IdentityData.LoginTime = record.LoginTime.Time.Format("2006-01-02T15:04:05Z")
		accessEventDTOs = append(accessEventDTOs, ev)
	}

	return accessEventDTOs
}
